package booksystem.dao.impl;

import booksystem.dao.BaseDao;
import booksystem.dao.UserDao;
import booksystem.entity.User;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class UserDaoImpl extends BaseDao<User> implements UserDao {
    @Override
    public int save(User user) {
        String sql = "insert into user(id, username, password, email, phone, register_time) value(?,?,?,?,?,?)";
        // 注册时间，获取当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return update(sql, user.getId(), user.getUsername(), user.getPassword(), user.getEmail(), user.getPhone(), sdf.format(date));
    }

    @Override
    public User emailLogin(String account, String password) {
        String sql = "select id,username,email,phone from user where email=? and password=?";
        return getBean(User.class, sql, account, password);
    }

    @Override
    public User phoneLogin(String account, String password) {
        String sql = "select id,username,email,phone from user where phone=? and password=?";
        return getBean(User.class, sql, account, password);
    }

    @Override
    public int changePassword(String username, String oldPassword, String newPassword) {
        String sql = "update user set password=? where email=? and password=?";
        return update(sql, newPassword, username, oldPassword);
    }

    @Override
    public List<User> getAllUser() {
        String sql = "select * from user";
        return getBeanList(User.class, sql);
    }

    @Override
    public User getUser(String id) {
        String sql = "select * from user where id=?";
        return getBean(User.class, sql, id);
    }

    @Override
    public int deleteUser(String id) {
        String sql = "delete from user where id=?";
        return update(sql, id);
    }
}
